package com.codingx.validator;
import com.codingx.validator.model.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ValidationException;
/**
 * 全局异常处理
 * 因为参数校验会抛出几种不同的校验异常，索性都捕获了
 * @param <T>
 */
@Slf4j
@RestControllerAdvice
public class GlobalExecptionHandler<T> {
    //方法参数校验异常
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public RestResponse<T> validationHandler(MethodArgumentNotValidException e){
        StringBuffer sb = new StringBuffer("");
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            sb.append(",[").append(error.getDefaultMessage()).append("]");
        }
        return RestResponse.fail(sb.substring(1));
    }
    //校验异常
    @ExceptionHandler(value= ValidationException.class)
    public RestResponse<T> validationHandler(ValidationException e){
        return RestResponse.fail(e.getMessage());
    }
    //不合法参数异常，针对SpringBoot Assert断言抛出的异常
    @ExceptionHandler(value= IllegalArgumentException.class)
    public RestResponse<T> validationHandler(IllegalArgumentException e){
        return RestResponse.fail(e.getMessage());
    }
    //其他异常
    @ExceptionHandler(value=Throwable.class)
    public RestResponse<T> execptionHandler(Throwable e){
        log.error("系统异常",e);
        return RestResponse.fail("系统异常");
    }
}
